package com.bayi.storage.network.entity;

import com.alibaba.fastjson.JSONException;
import com.bayi.storage.network.RetrofitHelper;
import com.bayi.storage.utils.LogUtil;
import com.bayi.storage.utils.ToastUtil;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * @author xp
 * Create on 16/1/2.
 */
public abstract class ApiSubscriber<T> extends Subscriber<T> {


    public ApiSubscriber() {

    }


    @Override
    public void onStart() {
    }

    @Override
    public void onCompleted() {

    }

    /**
     * 请求数据
     *
     * @param entity
     */
    protected abstract void callback(int code, T entity);

    /**
     * 请求数据错误
     *
     * @param entity
     */
    protected abstract void callbackError(int code, String entity);

    @Override
    public void onNext(T t) {
        if (t != null & ((ResponseDataBody) t).code == RetrofitHelper.CODE) {
            callback(((ResponseDataBody) t).code, t);
        } else {
            int code = ((ResponseDataBody) t).code;
            String message = ((ResponseDataBody) t).msg;
            callbackError(code, message);
        }

    }

    /**
     * 只要链式调用中抛出了异常都会走这个回调
     */
    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException) {
            callbackError(999, e.toString());
        } else if (e instanceof ApiException) {
            //服务器返回的错误
            LogUtil.e("NETWORKURL", String.valueOf(((ApiException) e).getCode()));
            callbackError(999, String.valueOf(e));
        } else if (e instanceof ConnectException || e instanceof UnknownHostException) {
            callbackError(999, "网络异常，请检查网络");
//            ToastUtil.show("网络异常，请检查网络");
        } else if (e instanceof TimeoutException || e instanceof SocketTimeoutException) {
            callbackError(999, "网络不畅，请稍后再试");
            ToastUtil.show("网络不畅，请稍后再试！");
        } else if (e instanceof JSONException) {
            callbackError(999, "数据解析异常");
            ToastUtil.show("数据解析异常");
        } else {
            callbackError(999, "服务端错误");
            ToastUtil.show("服务端错误");
        }
        e.printStackTrace();
    }
}
